// 导入Three.js单例，确保整个应用中只有一个Three.js实例
import { THREE, GLTFLoader, OrbitControls, VRButton } from './core/three-singleton.js';
import { AICharacter } from './AICharacter.js';
import { VoiceManager } from './VoiceManager.js';
import { UIManager } from './UIManager.js';
import { AudioManager } from './AudioManager.js';
import { UnifiedXRManager } from './core/UnifiedXRManager.js';
// UnifiedGestureHandler已移除，手势功能统一到HandTrackingManager
import { PerformanceManager } from './utils/PerformanceManager.js';
import { ImmersiveSceneManager } from './ImmersiveSceneManager.js';
import { appConfig } from './config/app-config.js';
import { ENV_CONFIG } from './config/env-config.js';
import { PoetSelector } from './PoetSelector.js';
import { Poet3DCharacter } from './Poet3DCharacter.js';
import { ImmersiveExperience } from './ImmersiveExperience.js';
import { SCENE_TYPES } from './config/immersive-scenes-config.js';
import { ProgressManager } from './ProgressManager.js';

class VisionProAIScene {
    constructor() {
        // 核心组件
        this.scene = null;
        this.camera = null;
        this.renderer = null;
        this.controls = null;
        
        // 增强功能
        this.unifiedXRManager = null;
        // 手势处理统一使用UnifiedXRManager中的HandTrackingManager
        this.immersiveExperience = null;
        
        // AI角色和管理器
        this.aiCharacter = null;
        this.poet3DCharacter = null;
        this.voiceManager = null;
        this.uiManager = null;
        this.audioManager = null;
        this.poetSelector = null;
        this.mixer = null;
        
        // 状态管理
        this.isVRMode = false;
        this.isConnected = false;
        this.isThinking = false;
        this.currentEnvironment = 'default';
        this.currentAnimation = null;
        this.animations = {};
        
        // API配置 - 从配置文件获取
        this.apiConfig = appConfig.apiConfig;
        this.apiBaseUrl = appConfig.getApiUrl();
        
        // 语音相关
        this.recognition = null;
        this.isListening = false;
        this.currentAudio = null;
        
        // UI元素
        this.elements = {};
        
        // 设置
        this.settings = {
            autoPlay: true,
            voiceEnabled: true,
            animationsEnabled: true,
            environmentType: 'default', // 'default', 'realistic'
            characterModel: 'default'
        };
        
        // 性能管理
        this.performanceManager = null;
        this.frameSkipCounter = 0;
        this.targetFrameRate = 60;
        this.adaptiveFrameRate = true;
        
        // 进度管理
        this.progressManager = new ProgressManager();
        
        this.clock = new THREE.Clock();
        this.init();
    }

    // 初始化统一WebXR管理器
    async initUnifiedXRManager() {
        try {
            // 存储引用到window对象，确保UnifiedXRManager可以访问app实例
            window.app = this;
            
            this.unifiedXRManager = new UnifiedXRManager(this.renderer, this.scene, this.camera, {
                createVRButton: false,
                immersiveSceneManager: this.immersiveSceneManager
            });
            await this.unifiedXRManager.init();
            
            // 使用UnifiedXRManager中的HandTrackingManager，避免重复初始化
            // 设置手势事件监听器
            if (this.unifiedXRManager.handTrackingManager) {
                this.unifiedXRManager.handTrackingManager.onGestureDetected = (gesture) => {
                    this.handleGesture(gesture);
                };
            }
            
            this.unifiedXRManager.onObjectSelected = (object) => {
                this.handleVRObjectSelection(object);
            };
            
            // 监听角色交互事件
            document.addEventListener('character-interaction', (event) => {
                this.handleCharacterInteraction(event.detail.character);
            });
            
            console.log('统一WebXR管理器初始化完成');
        } catch (error) {
            console.warn('统一WebXR管理器初始化失败:', error);
        }
    }

    // 处理VR对象选择
    handleVRObjectSelection(object) {
        console.log('VR对象选择:', object);
        
        // 如果选择的是AI角色
        if (object.userData && object.userData.type === 'ai-character') {
            this.switchCharacter(object.userData.characterType);
        }
        
        // 如果选择的是环境对象
        if (object.userData && object.userData.type === 'environment') {
            this.handleEnvironmentInteraction(object);
        }
    }

    // 处理VR手势
    handleVRGesture(gesture) {
        console.log('VR手势检测:', gesture);
        
        switch (gesture.type) {
            case 'pinch':
                this.handleVRPinch(gesture);
                break;
            case 'point':
                this.handleVRPoint(gesture);
                break;
            case 'grab':
                this.handleVRGrab(gesture);
                break;
            case 'wave':
                this.handleVRWave(gesture);
                break;
        }
    }

    // 处理VR对话触发
    handleVRDialogue(character) {
        console.log('VR对话触发:', character);
        
        // 切换到对应角色并开始对话
        if (character && character.userData && character.userData.characterType) {
            this.switchCharacter(character.userData.characterType);
            
            // 显示VR对话界面
            // 在VR模式下显示对话界面
        if (this.unifiedXRManager && this.unifiedXRManager.handTrackingManager) {
            console.log('VR对话模式激活');
        }
        }
    }

    // 处理VR捏取手势
    handleVRPinch(gesture) {
        // 实现VR捏取逻辑
        if (gesture.target) {
            console.log('VR捏取手势:', gesture.target);
            // 基础的对象操作逻辑
            if (gesture.target.userData && gesture.target.userData.interactive) {
                gesture.target.scale.multiplyScalar(1.1);
            }
        }
    }

    // 处理VR指向手势
    handleVRPoint(gesture) {
        // 实现VR指向逻辑
        if (gesture.target) {
            console.log('VR指向手势:', gesture.target);
            // 基础的高亮逻辑
            if (gesture.target.material) {
                gesture.target.material.emissive.setHex(0x444444);
            }
        }
    }

    // 处理VR抓取手势
    handleVRGrab(gesture) {
        // 实现VR抓取逻辑
        if (gesture.target) {
            console.log('VR抓取手势:', gesture.target);
            // 基础的抓取逻辑
            if (gesture.target.userData) {
                gesture.target.userData.grabbed = true;
            }
        }
    }

    // 处理VR挥手手势
    handleVRWave(gesture) {
        // 实现VR挥手逻辑
        // 可以用于问候AI角色或触发特殊动画
        if (this.aiCharacter) {
            this.aiCharacter.playAnimation('greeting');
        }
    }

    // 处理环境交互
    handleEnvironmentInteraction(object) {
        console.log('环境交互:', object);
        
        // 根据对象类型执行不同的交互
        if (object.userData.interactionType === 'teleport') {
            this.handleVRTeleport(object.position);
        } else if (object.userData.interactionType === 'info') {
            this.showObjectInfo(object);
        }
    }

    // 处理VR传送
    handleVRTeleport(position) {
        if (this.camera && this.renderer.xr.isPresenting) {
            // 平滑传送到新位置
            const targetPosition = position.clone();
            targetPosition.y += 1.6; // 调整到用户眼睛高度
            
            // 使用动画传送
            this.animateCameraTo(targetPosition);
        }
    }

    // 动画移动相机
    animateCameraTo(targetPosition) {
        // 设置相机动画状态，由主渲染循环处理
        this.cameraAnimation = {
            startPosition: this.camera.position.clone(),
            targetPosition: targetPosition.clone(),
            duration: 1000, // 1秒
            startTime: Date.now(),
            active: true
        };
    }

    /**
     * 更新相机动画（由主渲染循环调用）
     */
    updateCameraAnimation() {
        if (!this.cameraAnimation || !this.cameraAnimation.active) {
            return;
        }

        const elapsed = Date.now() - this.cameraAnimation.startTime;
        const progress = Math.min(elapsed / this.cameraAnimation.duration, 1);
        
        // 使用缓动函数
        const easeProgress = 1 - Math.pow(1 - progress, 3);
        
        this.camera.position.lerpVectors(
            this.cameraAnimation.startPosition, 
            this.cameraAnimation.targetPosition, 
            easeProgress
        );
        
        if (progress >= 1) {
            this.cameraAnimation.active = false;
            if (this.cameraAnimation.callback) {
                this.cameraAnimation.callback();
            }
        }
    }

    // 显示对象信息
    showObjectInfo(object) {
        if (object.userData && object.userData.info) {
            console.log('显示对象信息:', object.userData.info);
            // 可以在这里添加基础的信息显示逻辑
        }
    }

    // 初始化环境
    async initEnvironment() {
        try {
            // 使用默认Three.js环境
            this.setupDefaultEnvironment();
            console.log('默认环境设置完成');
        } catch (error) {
            console.warn('环境初始化失败，使用默认环境:', error);
            this.setupDefaultEnvironment();
        }
    }

    // 设置默认环境
    setupDefaultEnvironment() {
        // 添加环境光
        const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
        this.scene.add(ambientLight);

        // 添加主光源
        const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0);
        directionalLight.position.set(5, 10, 5);
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize.width = 2048;
        directionalLight.shadow.mapSize.height = 2048;
        this.scene.add(directionalLight);

        // 添加补光
        const fillLight = new THREE.DirectionalLight(0x87CEEB, 0.3);
        fillLight.position.set(-5, 5, -5);
        this.scene.add(fillLight);

        // 地面由场景文件提供，不需要额外创建
    }

    async initAudioManager() {
        try {
            this.audioManager = new AudioManager({
                volume: 0.8,
                enableVisualization: true,
                enableSubtitles: true,
                autoPlay: true,
                enableLipSync: true  // 启用唇语同步
            });

            // 设置音频事件回调
            this.audioManager.on('play', (data) => {
                console.log('音频开始播放');
                if (this.aiCharacter) {
                    this.aiCharacter.playAnimation('speaking');
                    // 启用角色的唇语同步
                    this.aiCharacter.enableLipSync();
                }
            });

            this.audioManager.on('end', (data) => {
                console.log('音频播放结束');
                if (this.aiCharacter) {
                    this.aiCharacter.playAnimation('idle');
                    // 禁用角色的唇语同步并重置嘴部形状
                    this.aiCharacter.disableLipSync();
                }
                // 停止实时字幕
                if (this.uiManager) {
                    this.uiManager.stopRealtimeSubtitles();
                }
            });

            this.audioManager.on('progress', (progress) => {
                // 更新播放进度
                if (this.uiManager) {
                    this.uiManager.updateAudioProgress(progress);
                }
            });

            this.audioManager.on('visualizationData', (data) => {
                // 根据音频数据调整角色动画
                if (this.aiCharacter && data.features) {
                    this.aiCharacter.updateAudioVisualization(data.features);
                }
            });

            // 添加唇语同步回调
            this.audioManager.on('onLipSyncData', (lipSyncData) => {
                // 将唇语同步数据传递给角色
                if (this.aiCharacter) {
                    this.aiCharacter.updateLipSync(lipSyncData);
                }
            });

            console.log('音频管理器初始化成功，唇语同步已启用');
        } catch (error) {
            console.error('音频管理器初始化失败:', error);
        }
    }

    async init() {
        // 确保在try-catch外部也能隐藏加载界面和启动渲染循环
        let initSuccess = false;
        
        try {
            console.log('开始初始化Vision Pro AI场景...');
            
            // 开始进度管理
            this.progressManager.startLoading();
            
            // 初始化Three.js场景
            console.log('初始化Three.js场景...');
            this.progressManager.updateProgress(10, '初始化3D场景...');
            await this.initScene();
            
            // 初始化统一WebXR管理器
            console.log('初始化统一WebXR管理器...');
            this.progressManager.updateProgress(20, '初始化WebXR管理器...');
            await this.initUnifiedXRManager();
            
            // 初始化环境
            console.log('初始化环境...');
            this.progressManager.updateProgress(30, '初始化环境...');
            await this.initEnvironment();
            
            // 初始化UI - 确保在沉浸式体验系统之前初始化
            console.log('初始化UI...');
            this.progressManager.updateProgress(40, '初始化用户界面...');
            await this.initUI();
            console.log('✅ UI初始化完成');
            
            // 先初始化语音管理器，以便ImmersiveExperience可以复用
            console.log('初始化语音管理器...');
            this.progressManager.updateProgress(50, '初始化语音系统...');
            await this.initVoiceManager();
            
            // 现在在UI和语音管理器初始化完成后再初始化沉浸式体验系统
            console.log('初始化沉浸式体验系统...');
            this.progressManager.updateProgress(60, '初始化沉浸式体验...');
            await this.initImmersiveExperience();
            
            // 初始化诗人选择器
            console.log('初始化诗人选择器...');
            this.progressManager.updateProgress(70, '初始化诗人选择器...');
            await this.initPoetSelector();
            
            // 初始化音频管理器
            console.log('初始化音频管理器...');
            this.progressManager.updateProgress(80, '初始化音频系统...');
            await this.initAudioManager();
            
            // 跳过默认AI角色加载，统一由沉浸式场景管理器处理
            console.log('跳过默认AI角色加载，统一由沉浸式场景管理器处理');
            this.progressManager.updateProgress(90, '加载AI角色...');
            
            // 检查API连接
            console.log('检查API连接...');
            this.progressManager.updateProgress(95, '检查API连接...');
            await this.checkAPIConnection();
            
            initSuccess = true;
            console.log('初始化成功完成');
            
        } catch (error) {
            console.error('初始化过程中出现错误:', error);
            // 不在这里调用hideLoading，确保无论如何都会执行渲染循环
        } finally {
            // 确保渲染循环总是启动，无论初始化是否成功
            console.log('开始渲染循环...');
            try {
                this.animate();
            } catch (animError) {
                console.error('启动渲染循环失败:', animError);
            }
            
            // 确保加载界面总是隐藏
            console.log('隐藏加载界面...');
            try {
                this.hideLoading();
                if (initSuccess) {
                    this.progressManager.updateProgress(100, '初始化完成！');
                    setTimeout(() => {
                        this.progressManager.hide();
                    }, 1000);
                    this.showNotification('Vision Pro AI场景初始化完成！', 'success');
                } else {
                    this.progressManager.updateProgress(100, '初始化部分失败');
                    setTimeout(() => {
                        this.progressManager.hide();
                    }, 2000);
                    this.showError('初始化部分失败', '部分组件初始化失败，但应用仍可运行');
                }
            } catch (hideError) {
                console.error('隐藏加载界面失败:', hideError);
            }
        }
    }

    async initScene() {
        // 创建场景
        this.scene = new THREE.Scene();
        this.scene.background = new THREE.Color(0x87CEEB); // 天空蓝

        // 创建相机
        this.camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth / window.innerHeight,
            0.1,
            1000
        );
        this.camera.position.set(0, 1.6, 3);

        // 创建渲染器
        this.renderer = new THREE.WebGLRenderer({ 
            antialias: true,
            alpha: true 
        });
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        this.renderer.outputColorSpace = THREE.SRGBColorSpace;
        
        // WebXR支持
        this.renderer.xr.enabled = true;
        
        document.getElementById('main-container').appendChild(this.renderer.domElement);

        // 添加WebXR按钮
        const vrButton = this.createEnhancedVRButton();
        document.getElementById('vr-button-container').appendChild(vrButton);

        // 创建控制器
        this.controls = new OrbitControls(this.camera, this.renderer.domElement);
        this.setupOrbitControls();

        // 初始化性能管理器
        this.performanceManager = new PerformanceManager(this.renderer, this.scene, this.camera);
        
        // 设置ModelLoader的renderer引用以支持纹理优化
        if (this.modelLoader) {
            this.modelLoader.renderer = this.renderer;
        }
        
        // 注意：沉浸式体验系统的初始化移至UnifiedXRManager初始化之后
        // 这样可以确保UnifiedXRManager实例已创建并传递给ImmersiveExperience

        // 监听窗口大小变化
        window.addEventListener('resize', () => this.onWindowResize());
        
        // VR模式变化由统一XR管理器处理，通过自定义事件通知
        document.addEventListener('xrstart', () => {
            this.isVRMode = true;
            this.onVRModeChange();
        });
        
        document.addEventListener('xrend', () => {
            this.isVRMode = false;
            this.onVRModeChange();
        });
        

    }

    // 初始化沉浸式体验系统
    async initImmersiveExperience() {
        try {
            console.log('初始化沉浸式体验系统...');
            
            // 创建沉浸式体验实例，传入已初始化的UnifiedXRManager实例
            this.immersiveExperience = new ImmersiveExperience(
                this.renderer,
                this.scene,
                this.camera,
                {
                    unifiedXRManager: this.unifiedXRManager
                }
            );
            
            // 初始化系统
            await this.immersiveExperience.init();
            
            // 移除重复默认场景加载，改由 sceneManager.init 内部处理
            
            // 设置事件监听器
            this.immersiveExperience.addEventListener('immersive:sceneloaded', (event) => {
                console.log('场景加载完成:', event.detail);
            });
            
            this.immersiveExperience.addEventListener('immersive:characterloaded', (event) => {
                console.log('角色加载完成:', event.detail);
            });
            
            console.log('沉浸式体验系统初始化完成');
            
        } catch (error) {
            console.error('沉浸式体验系统初始化失败:', error);
            // 回退到基础环境
            this.setupLighting();
            this.createEnvironment();
        }
    }

    setupLighting() {
        // 优化的环境光 - 提高强度减少对其他光源的依赖
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
        this.scene.add(ambientLight);

        // 主光源 - 优化阴影设置
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
        directionalLight.position.set(5, 10, 5);
        directionalLight.castShadow = true;
        
        // 优化阴影贴图大小以提高性能
        directionalLight.shadow.mapSize.width = 1024;
        directionalLight.shadow.mapSize.height = 1024;
        directionalLight.shadow.camera.near = 0.5;
        directionalLight.shadow.camera.far = 30; // 减少阴影距离
        directionalLight.shadow.camera.left = -8;
        directionalLight.shadow.camera.right = 8;
        directionalLight.shadow.camera.top = 8;
        directionalLight.shadow.camera.bottom = -8;
        
        // 优化阴影偏移以减少阴影失真
        directionalLight.shadow.bias = -0.0001;
        this.scene.add(directionalLight);

        // 移除补光以提高性能 - 环境光已经足够
        // 如果需要补光，使用不投射阴影的光源
        const fillLight = new THREE.HemisphereLight(0x87CEEB, 0x8B4513, 0.3);
        this.scene.add(fillLight);
    }

    createEnvironment() {
        // 地面由场景文件提供，不需要额外创建

        // 创建背景几何体
        const sphereGeometry = new THREE.SphereGeometry(50, 32, 32);
        const sphereMaterial = new THREE.MeshBasicMaterial({
            color: 0x87CEEB,
            side: THREE.BackSide,
            transparent: true,
            opacity: 0.3
        });
        const backgroundSphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        this.scene.add(backgroundSphere);

        // 添加一些装饰性几何体
        this.addDecorations();
    }

    addDecorations() {
        // 添加一些浮动的几何体作为装饰
        const geometries = [
            new THREE.BoxGeometry(0.5, 0.5, 0.5),
            new THREE.SphereGeometry(0.3, 16, 16),
            new THREE.ConeGeometry(0.3, 0.8, 8)
        ];

        const materials = [
            new THREE.MeshPhongMaterial({ color: 0xff6b6b, transparent: true, opacity: 0.7 }),
            new THREE.MeshPhongMaterial({ color: 0x4ecdc4, transparent: true, opacity: 0.7 }),
            new THREE.MeshPhongMaterial({ color: 0xffe66d, transparent: true, opacity: 0.7 })
        ];

        for (let i = 0; i < 10; i++) {
            const geometry = geometries[Math.floor(Math.random() * geometries.length)];
            const material = materials[Math.floor(Math.random() * materials.length)];
            const mesh = new THREE.Mesh(geometry, material);
            
            mesh.position.set(
                (Math.random() - 0.5) * 15,
                Math.random() * 5 + 2,
                (Math.random() - 0.5) * 15
            );
            
            mesh.rotation.set(
                Math.random() * Math.PI,
                Math.random() * Math.PI,
                Math.random() * Math.PI
            );
            
            mesh.castShadow = true;
            this.scene.add(mesh);
            
            // 添加浮动动画
            this.animateDecoration(mesh);
        }
    }

    animateDecoration(mesh) {
        // 在mesh的userData中存储动画参数，由主渲染循环处理
        mesh.userData.originalY = mesh.position.y;
        mesh.userData.speed = 0.5 + Math.random() * 0.5;
        mesh.userData.amplitude = 0.5 + Math.random() * 0.5;
        
        // 将装饰对象添加到装饰数组中
        if (!this.decorations) {
            this.decorations = [];
        }
        this.decorations.push(mesh);
    }

    async loadAICharacter() {
        try {
            // 创建AI角色
            this.aiCharacter = new AICharacter(this.scene, {
                position: new THREE.Vector3(0, 0, 0),
                scale: 1,
                name: 'AI诗人'
            });
            
            // 等待角色模型加载完成
            if (this.aiCharacter.model) {
                // 设置角色为交互对象
                this.aiCharacter.model.userData = {
                    type: 'ai-character',
                    characterType: 'ai-poet',
                    interactive: true,
                    name: 'AI诗人'
                };
                
                // 注册到统一XR管理器
                if (this.unifiedXRManager) {
                    this.unifiedXRManager.addInteractableObject(this.aiCharacter.model);
                }
                
                // 角色交互由HandTrackingManager处理
                console.log('AI角色已加载并注册为可交互对象');
            }
            
            console.log('AI角色加载完成并注册为交互对象');
        } catch (error) {
            console.error('AI角色加载失败:', error);
        }
    }

    async initVoiceManager() {
        this.voiceManager = new VoiceManager(this.apiBaseUrl);
        
        // 设置语音识别回调
        this.voiceManager.on('result', (transcript, confidence) => {
            if (this.uiManager) {
                this.sendMessage(transcript);
            } else {
                this.elements.textInput.value = transcript;
                this.sendMessage();
            }
        });
        
        this.voiceManager.on('start', () => {
            if (this.uiManager) {
                this.uiManager.updateVoiceStatus('正在听...', true);
            } else {
                this.elements.voiceBtn.classList.add('recording');
                this.elements.voiceStatus.textContent = '正在听...';
            }
            this.isListening = true;
        });
        
        this.voiceManager.on('end', () => {
            if (this.uiManager) {
                this.uiManager.updateVoiceStatus('点击开始语音输入', false);
            } else {
                this.elements.voiceBtn.classList.remove('recording');
                this.elements.voiceStatus.textContent = '点击开始语音输入';
            }
            this.isListening = false;
        });
        
        this.voiceManager.on('error', (error) => {
            if (this.uiManager) {
                this.uiManager.updateVoiceStatus('语音识别失败', false);
            } else {
                this.elements.voiceBtn.classList.remove('recording');
                this.elements.voiceStatus.textContent = '语音识别失败';
            }
            this.isListening = false;
            console.error('语音识别错误:', error);
        });
        
        this.voiceManager.on('connectionChange', (connected) => {
            this.isConnected = connected;
            this.updateConnectionStatus();
        });
    }

    async createPlaceholderCharacter() {
        // 这个方法现在由AICharacter类处理，保留以防需要
    }

    updateConnectionStatus() {
        if (this.uiManager) {
            this.uiManager.updateConnectionStatus(this.isConnected);
        } else {
            // 备用方法
            const statusElement = this.elements.connectionStatus;
            if (statusElement) {
                statusElement.textContent = this.isConnected ? '已连接' : '未连接';
                statusElement.className = `status-value ${this.isConnected ? 'connected' : 'disconnected'}`;
            }
        }
    }

    addBreathingAnimation() {
        if (!this.aiCharacter) return;
        
        // 设置呼吸动画标记，由主渲染循环处理
        this.breathingAnimation = true;
    }

    async initUI() {
        // 获取UI元素
        this.elements = {
            loadingScreen: document.getElementById('loading-screen'),
            controlPanel: document.getElementById('control-panel'),
            chatHistory: document.getElementById('chat-history'),
            textInput: document.getElementById('text-input'),
            sendBtn: document.getElementById('send-btn'),
            voiceBtn: document.getElementById('voice-btn'),
            voiceStatus: document.getElementById('voice-status'),
            statusIndicator: document.getElementById('status-indicator'),
            connectionStatus: document.querySelector('.status-value'),
            subtitles: document.getElementById('subtitles'),
            errorModal: document.getElementById('error-modal'),
            toggleBtn: document.querySelector('.toggle-btn'),
            voiceSelect: document.getElementById('voice-select'),
            autoPlayCheckbox: document.getElementById('auto-play-checkbox'),
            subtitlesCheckbox: document.getElementById('subtitles-checkbox')
        };

        // 验证关键元素是否存在
        const requiredElements = ['chatHistory', 'textInput', 'sendBtn'];
        for (const elementName of requiredElements) {
            if (!this.elements[elementName]) {
                console.warn(`缺少必需的UI元素: ${elementName}`);
            }
        }

        // 如果UI管理器还未创建，则创建它
        if (!this.uiManager) {
            this.uiManager = new UIManager(this.elements, {
                onSendMessage: (text) => this.sendMessage(text),
                onVoiceToggle: () => this.toggleVoiceRecognition(),
                onSettingsChange: (settings) => this.updateSettings(settings)
            });
        } else {
            // 如果已存在，则更新配置
            this.uiManager.updateConfig(this.elements, {
                onSendMessage: (text) => this.sendMessage(text),
                onVoiceToggle: () => this.toggleVoiceRecognition(),
                onSettingsChange: (settings) => this.updateSettings(settings)
            });
        }
        
        // 绑定基本事件
        this.bindBasicEvents();
        
        // 初始化语音识别（备用）
        this.initSpeechRecognition();
        
        // 添加欢迎消息
        if (this.elements.chatHistory) {
            this.addMessage('ai', '你好！我是AI诗人，很高兴在这个沉浸式空间与你对话。你可以通过文字或语音与我交流。');
        }
        
        // 为调试目的创建全局函数
        window.debugSubtitles = this.debugSubtitles.bind(this);
        console.log('全局调试函数 debugSubtitles() 已创建，可在控制台调用');
        
        // 记录UI初始化完成
        console.log('✅ UI初始化完成');
    }
    
    // 全局调试函数，用于测试字幕功能
    debugSubtitles(text = '这是一条测试字幕') {
        console.log('调试字幕:', text);
        
        // 检查subtitles元素是否存在
        console.log('subtitles元素存在:', !!this.elements.subtitles);
        
        if (!this.elements.subtitles) {
            console.error('subtitles元素不存在，无法显示字幕');
            return false;
        }
        
        // 获取subtitle-text元素
        const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
        console.log('subtitle-text元素存在:', !!subtitleText);
        
        // 显示subtitles元素的详细信息
        console.log('subtitles元素样式:', window.getComputedStyle(this.elements.subtitles));
        console.log('subtitles元素当前类名:', this.elements.subtitles.className);
        console.log('subtitles元素是否包含show类:', this.elements.subtitles.classList.contains('show'));
        console.log('subtitles元素位置信息:', {
            position: window.getComputedStyle(this.elements.subtitles).position,
            bottom: window.getComputedStyle(this.elements.subtitles).bottom,
            left: window.getComputedStyle(this.elements.subtitles).left,
            transform: window.getComputedStyle(this.elements.subtitles).transform,
            opacity: window.getComputedStyle(this.elements.subtitles).opacity,
            visibility: window.getComputedStyle(this.elements.subtitles).visibility
        });
        
        // 检查当前设置
        const settings = this.uiManager.getSettings();
        console.log('当前字幕设置:', settings.showSubtitles);
        
        // 显示字幕（忽略设置）
        console.log('强制显示字幕...');
        
        // 设置文本内容
        if (subtitleText) {
            subtitleText.textContent = text;
            console.log('已设置subtitle-text内容:', subtitleText.textContent);
        } else {
            // 如果没有找到subtitle-text元素，直接设置容器内容
            this.elements.subtitles.textContent = text;
            console.log('未找到subtitle-text元素，直接设置容器内容:', this.elements.subtitles.textContent);
        }
        
        // 强制显示
        this.elements.subtitles.classList.add('show');
        console.log('已添加show类，更新后的类名:', this.elements.subtitles.className);
        console.log('添加show类后是否包含show类:', this.elements.subtitles.classList.contains('show'));
        
        // 直接设置样式以确保可见性
        this.elements.subtitles.style.opacity = '1';
        this.elements.subtitles.style.visibility = 'visible';
        console.log('强制设置样式后的opacity:', window.getComputedStyle(this.elements.subtitles).opacity);
        console.log('强制设置样式后的visibility:', window.getComputedStyle(this.elements.subtitles).visibility);
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.elements.subtitles.classList.remove('show');
            this.elements.subtitles.style.opacity = '0';
            this.elements.subtitles.style.visibility = 'hidden';
            console.log('已移除show类，字幕隐藏');
        }, 3000);
        
        return true;
    }

    async initPoetSelector() {
        try {
            // 如果当前为 Supersplat 场景，则禁用 Poet3DCharacter，避免重复加载
            const isSupersplat = this.immersiveExperience?.sceneManager?.currentScene?.type === SCENE_TYPES.SUPERSPLAT_VIEWER;
            if (!isSupersplat) {
                this.poet3DCharacter = new Poet3DCharacter(this.scene, {
                    enablePreloading: true,
                    enableAnimations: true,
                    enableLighting: true
                });
                console.log('3D诗人角色管理器初始化完成');
            } else {
                this.poet3DCharacter = null;
                console.log('检测到 Supersplat 场景，禁用 Poet3DCharacter 以避免重复加载');
            }

            // 初始化诗人选择器，传入3D角色管理器（可能为 null）
            this.poetSelector = new PoetSelector(this.apiBaseUrl, this.poet3DCharacter, this.progressManager);
            
            // 监听诗人切换事件
            document.addEventListener('poetChanged', async (event) => {
                const { poetId, poetInfo } = event.detail;
                console.log('诗人已切换:', poetId, poetInfo);

                // 触发沉浸式场景切换
                if (this.immersiveExperience && poetId) {
                    try {
                        console.log('正在加载诗人场景:', poetId);
                        await this.immersiveExperience.loadPoetScene(poetId);
                        console.log('诗人场景加载完成:', poetId);
                    } catch (error) {
                        console.error('加载诗人场景失败:', error);
                        const name = poetInfo?.name || poetId;
                        this.showNotification(`加载${name}场景失败`, 'error');
                    }
                }

                const name = poetInfo?.name || poetId;
                const dynasty = poetInfo?.dynasty || '';
                this.showNotification(`已切换到${name}${dynasty ? `（${dynasty}）` : ''}`, 'success');
            });
            
            // 初始化诗人选择器
            await this.poetSelector.init();
            
        } catch (error) {
            console.error('初始化诗人选择器失败:', error);
            this.showNotification('诗人选择器初始化失败', 'error');
        }
    }

    bindBasicEvents() {
        // 发送按钮事件
        if (this.elements.sendBtn) {
            this.elements.sendBtn.addEventListener('click', () => {
                const text = this.elements.textInput?.value?.trim();
                if (text) {
                    this.sendMessage(text);
                    this.elements.textInput.value = '';
                }
            });
        }

        // 输入框回车事件
        if (this.elements.textInput) {
            this.elements.textInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const text = e.target.value.trim();
                    if (text) {
                        this.sendMessage(text);
                        e.target.value = '';
                    }
                }
            });
        }

        // 语音按钮事件
        if (this.elements.voiceBtn) {
            this.elements.voiceBtn.addEventListener('click', () => {
                this.toggleVoiceRecognition();
            });
        }

        // 面板切换事件
        if (this.elements.toggleBtn) {
            this.elements.toggleBtn.addEventListener('click', () => {
                this.togglePanel();
            });
        }
    }
    
    /**
     * 切换面板显示状态
     */
    togglePanel() {
        console.log('切换面板显示状态');
        
        if (this.elements.chatPanel) {
            const isOpen = this.elements.chatPanel.classList.contains('open');
            
            if (isOpen) {
                // 关闭面板
                this.elements.chatPanel.classList.remove('open');
                this.elements.chatPanel.classList.add('closed');
                console.log('✅ 聊天面板已关闭');
            } else {
                // 打开面板
                this.elements.chatPanel.classList.remove('closed');
                this.elements.chatPanel.classList.add('open');
                console.log('✅ 聊天面板已打开');
            }
            
            // 触发面板切换事件
            this.dispatchEvent('panelToggled', { isOpen: !isOpen });
        } else {
            console.warn('⚠️ 聊天面板元素未找到');
        }
    }

    bindEvents() {
        // 发送按钮
        this.elements.sendBtn.addEventListener('click', () => this.sendMessage());
        
        // 输入框回车
        this.elements.textInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        // 语音按钮
        this.elements.voiceBtn.addEventListener('click', () => this.toggleVoiceRecognition());
        
        // 面板折叠
        this.elements.toggleBtn.addEventListener('click', () => this.togglePanel());
        
        // 错误模态框关闭
        document.getElementById('close-error').addEventListener('click', () => this.hideError());
        

        
        // 设置复选框事件监听器
        const autoPlayCheckbox = document.getElementById('auto-play-checkbox');
        const subtitlesCheckbox = document.getElementById('subtitles-checkbox');
        
        if (autoPlayCheckbox) {
            autoPlayCheckbox.addEventListener('change', () => {
                this.updateSettings();
            });
        }
        
        if (subtitlesCheckbox) {
            subtitlesCheckbox.addEventListener('change', () => {
                this.updateSettings();
            });
        }

    }

    initSpeechRecognition() {
        if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
            const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
            this.recognition = new SpeechRecognition();
            this.recognition.continuous = false;
            this.recognition.interimResults = false;
            this.recognition.lang = 'zh-CN';
            
            this.recognition.onstart = () => {
                this.isListening = true;
                this.elements.voiceBtn.classList.add('recording');
                this.elements.voiceStatus.textContent = '正在听...';
            };
            
            this.recognition.onresult = (event) => {
                const transcript = event.results[0][0].transcript;
                this.elements.textInput.value = transcript;
                this.sendMessage();
            };
            
            this.recognition.onend = () => {
                this.isListening = false;
                this.elements.voiceBtn.classList.remove('recording');
                this.elements.voiceStatus.textContent = '点击开始语音输入';
            };
            
            this.recognition.onerror = (event) => {
                console.error('语音识别错误:', event.error);
                this.isListening = false;
                this.elements.voiceBtn.classList.remove('recording');
                this.elements.voiceStatus.textContent = '语音识别失败';
            };
        } else {
            this.elements.voiceBtn.style.display = 'none';
            console.warn('浏览器不支持语音识别');
        }
    }

    async checkAPIConnection() {
        if (this.voiceManager) {
            this.isConnected = await this.voiceManager.checkAPIConnection();
        } else {
            // 备用连接检查
            try {
                const response = await fetch(ENV_CONFIG.getHealthUrl());
                this.isConnected = response.ok;
            } catch (error) {
                this.isConnected = false;
                console.error('API连接检查失败:', error);
            }
        }
        this.updateConnectionStatus();
    }

    updateConnectionStatus() {
        const statusElement = document.querySelector('.status-value');
        if (statusElement) {
            statusElement.textContent = this.isConnected ? '已连接' : '未连接';
            statusElement.className = `status-value ${this.isConnected ? 'connected' : 'disconnected'}`;
        }
    }

    async sendMessage(text = null) {
        if (!text) {
            text = this.elements.textInput?.value?.trim();
        }
        if (!text) return;

        // 添加用户消息
        this.uiManager.addMessage('user', text);
        
        // 使用VoiceManager发送消息
        try {
            this.uiManager.updateThinkingStatus(true);
            
            if (this.aiCharacter) {
                this.aiCharacter.playAnimation('thinking');
            }
            
            // 播放思考动画
            if (this.poet3DCharacter) {
                this.poet3DCharacter.playThinkingAnimation();
            }
            
            const response = await this.voiceManager.sendMessage(text);
            
            if (response.reply) {
                this.uiManager.addMessage('ai', response.reply);
                
                const settings = this.uiManager.getSettings();
                
                // 播放语音 - 优先使用API音频，失败时回退到浏览器TTS
                if (settings.autoPlay) {
                    try {
                        if (response.audio_url) {
                            // 确保音频URL指向后端服务器
                            let audioUrl = response.audio_url;
                            if (audioUrl.startsWith('/audio/')) {
                                // 相对路径，转换为指向后端服务器的绝对URL
                                audioUrl = ENV_CONFIG.apiBaseUrl + audioUrl;
                            }
                            
                            // 尝试播放API生成的音频
                            if (this.audioManager) {
                                // 传递文本和音频时长以启用唇语同步
                                const playOptions = {
                                    text: response.reply,
                                    duration: response.duration || null
                                };
                                
                                // 设置一次性的播放回调，在音频真正开始播放时显示字幕
                                this.audioManager.off('play'); // 清除之前的监听器
                                this.audioManager.on('play', () => {
                                    // 显示字幕（基于固定时间间隔）
                                    if (settings.showSubtitles) {
                                        console.log('显示AI诗人回复字幕:', response.reply);
                                        // 使用基于固定时间间隔的字幕显示，每句话显示5秒
                                        this.uiManager.showIntervalBasedSubtitles(
                                            response.reply, 
                                            response.duration || 5 // 即使没有时长信息也提供默认值
                                        );
                                    }
                                    
                                    // 同时更新XR字幕
                                if (this.immersiveExperience && this.immersiveExperience.forceUpdateXRSubtitle) {
                                    console.log('🔄 同时更新XR字幕:', response.reply);
                                    this.immersiveExperience.forceUpdateXRSubtitle(response.reply, response.duration || 5, true); // 启用同步模式
                                }
                                });
                                
                                await this.audioManager.playAudio(audioUrl, playOptions);
                            } else {
                                await this.playAudio(audioUrl);
                            }
                        } else {
                            // 使用浏览器TTS作为回退
                            console.log('使用浏览器TTS播放语音');
                            const settings = this.uiManager.getSettings();
                            await this.voiceManager.textToSpeechBrowser(response.reply, {
                                onStart: (text) => {
                                    // 显示UI字幕
                                    if (settings.showSubtitles) {
                                        console.log('显示浏览器TTS字幕:', text);
                                        this.uiManager.showIntervalBasedSubtitles(
                                            text,
                                            response.duration || 5
                                        );
                                    }
                                    
                                    // 同时更新XR字幕
                                    if (this.immersiveExperience && this.immersiveExperience.forceUpdateXRSubtitle) {
                                        console.log('🔄 同时更新XR字幕:', text);
                                        this.immersiveExperience.forceUpdateXRSubtitle(text, response.duration || 5, true); // 启用同步模式
                                    }
                                }
                            });
                        }
                    } catch (audioError) {
                        console.warn('API音频播放失败，回退到浏览器TTS:', audioError);
                        try {
                            // 添加onStart回调以显示基于固定时间间隔的字幕和XR字幕
                                const settings = this.uiManager.getSettings();
                                await this.voiceManager.textToSpeechBrowser(response.reply, {
                                    onStart: (text) => {
                                        // 显示UI字幕
                                        if (settings.showSubtitles) {
                                            console.log('显示浏览器TTS字幕:', text);
                                            this.uiManager.showIntervalBasedSubtitles(
                                                text,
                                                response.duration || 5
                                            );
                                        }
                                        
                                        // 同时更新XR字幕
                                    if (this.immersiveExperience && this.immersiveExperience.forceUpdateXRSubtitle) {
                                        console.log('🔄 同时更新XR字幕:', text);
                                        this.immersiveExperience.forceUpdateXRSubtitle(text, response.duration || 5, true); // 启用同步模式
                                    }
                                    }
                                });
                            } catch (ttsError) {
                                console.error('浏览器TTS也失败了:', ttsError);
                            }
                    }
                    
                    // 控制3D诗人角色说话动画
                    if (this.poet3DCharacter) {
                        this.poet3DCharacter.startSpeaking();
                    }
                }
                
                // 播放动画
                if (response.animation) {
                    this.playAnimation(response.animation);
                } else if (this.aiCharacter) {
                    this.aiCharacter.playAnimation('idle');
                }
            }
        } catch (error) {
            console.error('发送消息失败:', error);
            this.uiManager.addMessage('ai', '抱歉，我现在无法回复。请检查网络连接或稍后再试。');
            this.uiManager.showError('发送失败', error.message);
        } finally {
            this.uiManager.updateThinkingStatus(false);
            
            // 停止思考动画，切换到空闲状态
            if (this.poet3DCharacter) {
                this.poet3DCharacter.stopSpeaking(); // 这会切换到idle动画
            }
        }
    }

    // 添加消息到聊天历史
    addMessage(type, content, timestamp = null) {
        if (this.uiManager) {
            this.uiManager.addMessage(type, content, timestamp);
        } else {
            // 备用方法，直接操作DOM
            const chatHistory = document.getElementById('chat-history');
            if (chatHistory) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${type}`;
                
                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content';
                contentDiv.textContent = content;
                messageDiv.appendChild(contentDiv);
                
                const timeDiv = document.createElement('div');
                timeDiv.className = 'message-time';
                timeDiv.textContent = timestamp || new Date().toLocaleTimeString();
                messageDiv.appendChild(timeDiv);
                
                chatHistory.appendChild(messageDiv);
                chatHistory.scrollTop = chatHistory.scrollHeight;
            }
        }
    }

    // 显示错误信息
    showError(title, message) {
        if (this.uiManager) {
            this.uiManager.showError(title, message);
        } else {
            console.error(`${title}: ${message}`);
            alert(`${title}: ${message}`);
        }
    }

    // 显示通知
    showNotification(message, type = 'info') {
        if (this.uiManager) {
            this.uiManager.showNotification(message, type);
        } else {
            console.log(`${type.toUpperCase()}: ${message}`);
        }
    }

    // 隐藏加载界面
    hideLoading() {
        // 进度管理器已经负责隐藏进度条，这里只处理UI管理器的加载界面
        if (this.uiManager) {
            this.uiManager.hideLoading();
        }
        // 不再直接操作loading-screen元素，由进度管理器统一管理
    }

    async playAudio(audioUrl) {
        try {
            if (this.audioManager) {
                // 使用AudioManager播放音频
                await this.audioManager.playAudio(audioUrl);
            } else {
                // 回退到基础音频播放
                if (this.currentAudio) {
                    this.currentAudio.pause();
                }
                
                this.currentAudio = new Audio(audioUrl);
                await this.currentAudio.play();
            }
        } catch (error) {
            console.error('音频播放失败:', error);
        }
    }

    showSubtitles(text) {
        // 获取当前设置
        const currentSettings = this.uiManager ? this.uiManager.getSettings() : { showSubtitles: true };
        
        console.log('字幕显示请求，当前设置:', currentSettings.showSubtitles);
        
        if (currentSettings.showSubtitles) {
            console.log('显示字幕:', text);
            
            // 使用subtitle-text元素显示字幕
            const subtitleText = this.elements.subtitles.querySelector('#subtitle-text');
            if (subtitleText) {
                subtitleText.textContent = text;
            } else {
                this.elements.subtitles.textContent = text;
            }
            
            this.elements.subtitles.classList.add('show');
            this.elements.subtitles.style.opacity = '1';
            this.elements.subtitles.style.visibility = 'visible';
            
            setTimeout(() => {
                this.elements.subtitles.classList.remove('show');
                this.elements.subtitles.style.opacity = '0';
                this.elements.subtitles.style.visibility = 'hidden';
            }, 3000);
        } else {
            console.log('字幕设置为隐藏，不显示字幕');
            // 如果设置为不显示，确保字幕被隐藏
            if (this.elements.subtitles) {
                this.elements.subtitles.classList.remove('show');
                this.elements.subtitles.style.opacity = '0';
                this.elements.subtitles.style.visibility = 'hidden';
            }
        }
    }

    playAnimation(animationType) {
        if (this.aiCharacter && this.aiCharacter.playAnimation) {
            this.aiCharacter.playAnimation(animationType);
        } else {
            // 备用动画系统
            switch (animationType) {
                case 'bounce':
                    this.bounceAnimation();
                    break;
                case 'thinking':
                    this.thinkingAnimation();
                    break;
                case 'wave':
                    this.waveAnimation();
                    break;
                default:
                    this.idleAnimation();
            }
        }
    }

    bounceAnimation() {
        if (!this.aiCharacter || !this.aiCharacter.character) return;
        
        const character = this.aiCharacter.character;
        if (!character.userData) character.userData = {};
        
        character.userData.bounceAnimation = {
            startTime: Date.now(),
            duration: 1000,
            originalY: character.position.y
        };
    }

    thinkingAnimation() {
        if (!this.aiCharacter || !this.aiCharacter.character) return;
        
        const character = this.aiCharacter.character;
        if (!character.userData) character.userData = {};
        
        character.userData.thinkingAnimation = {
            startTime: Date.now(),
            duration: 2000,
            originalRotationY: character.rotation.y
        };
    }

    waveAnimation() {
        if (!this.aiCharacter || !this.aiCharacter.character) return;
        
        const character = this.aiCharacter.character;
        const rightArm = character.children && character.children.find ? character.children.find(child => 
            child.position.x > 0 && child.geometry instanceof THREE.CylinderGeometry
        ) : null;
        
        if (rightArm) {
            if (!rightArm.userData) rightArm.userData = {};
            rightArm.userData.waveAnimation = {
                startTime: Date.now(),
                duration: 1500,
                originalRotationZ: rightArm.rotation.z
            };
        }
    }

    idleAnimation() {
        // 默认的空闲动画已经在 addBreathingAnimation 中实现
    }

    toggleVoiceRecognition() {
        if (this.voiceManager) {
            this.voiceManager.toggleListening();
        } else if (this.recognition) {
            // 备用语音识别
            if (this.isListening) {
                this.recognition.stop();
            } else {
                this.recognition.start();
            }
        }
    }



    setThinkingStatus(thinking) {
        const statusValue = document.querySelector('.status-value.thinking') || 
                          document.querySelector('.status-value');
        if (statusValue) {
            if (thinking) {
                statusValue.textContent = '思考中...';
                statusValue.className = 'status-value thinking';
            } else {
                statusValue.textContent = this.isConnected ? '已连接' : '未连接';
                statusValue.className = `status-value ${this.isConnected ? 'connected' : 'disconnected'}`;
            }
        }
    }

    showError(title, message) {
        const errorTitle = document.getElementById('error-title');
        const errorMessage = document.getElementById('error-message');
        
        if (errorTitle) {
            errorTitle.textContent = title;
        }
        if (errorMessage) {
            errorMessage.textContent = message;
        }
        
        if (this.elements && this.elements.errorModal) {
            this.elements.errorModal.classList.add('show');
        } else {
            const errorModal = document.getElementById('error-modal');
            if (errorModal) {
                errorModal.classList.add('show');
            }
        }
    }

    hideError() {
        this.elements.errorModal.classList.remove('show');
    }

    // 处理手势识别
    handleGesture(gesture) {
        console.log('检测到手势:', gesture);
        
        switch (gesture.type) {
            case 'tap':
                // 点击手势 - 发送消息或触发交互
                if (this.aiCharacter) {
                    this.aiCharacter.playAnimation('wave');
                }
                break;
                
            case 'pinch':
                // 捏合手势 - 缩放或选择
                this.handlePinchGesture(gesture);
                break;
                
            case 'swipe':
                // 滑动手势 - 切换场景或角色
                this.handleSwipeGesture(gesture);
                break;
                
            case 'point':
                // 指向手势 - 选择或高亮
                this.handlePointGesture(gesture);
                break;
        }
    }

    // 处理语音命令
    handleVoiceCommand(command) {
        console.log('检测到语音命令:', command);
        
        const lowerCommand = command.toLowerCase();
        
        if (lowerCommand.includes('你好') || lowerCommand.includes('hello')) {
            this.sendMessage('你好！');
        } else if (lowerCommand.includes('切换场景') || lowerCommand.includes('change scene')) {
            this.switchEnvironment();
        } else if (lowerCommand.includes('切换角色') || lowerCommand.includes('change character')) {
            this.switchCharacter();

        } else if (lowerCommand.includes('播放动画') || lowerCommand.includes('play animation')) {
            if (this.aiCharacter) {
                this.aiCharacter.playAnimation('idle');
            }
        } else {
            // 将其他语音命令作为消息发送
            this.sendMessage(command);
        }
    }

    // 处理捏合手势
    handlePinchGesture(gesture) {
        if (gesture.scale) {
            // 缩放AI角色
            if (this.aiCharacter && this.aiCharacter.model) {
                const currentScale = this.aiCharacter.model.scale.x;
                const newScale = Math.max(0.5, Math.min(2.0, currentScale * gesture.scale));
                this.aiCharacter.model.scale.setScalar(newScale);
            }
        }
    }

    // 处理滑动手势
    handleSwipeGesture(gesture) {
        if (gesture.direction === 'left') {
            this.switchToPreviousEnvironment();
        } else if (gesture.direction === 'right') {
            this.switchToNextEnvironment();
        }
    }

    // 处理指向手势
    handlePointGesture(gesture) {
        // 实现射线投射来检测指向的对象
        if (gesture.position && this.camera) {
            const raycaster = new THREE.Raycaster();
            const mouse = new THREE.Vector2();
            
            // 将手势位置转换为标准化设备坐标
            mouse.x = (gesture.position.x / window.innerWidth) * 2 - 1;
            mouse.y = -(gesture.position.y / window.innerHeight) * 2 + 1;
            
            raycaster.setFromCamera(mouse, this.camera);
            
            // 检测与AI角色的交互
            if (this.aiCharacter && this.aiCharacter.model) {
                const intersects = raycaster.intersectObject(this.aiCharacter.model, true);
                if (intersects.length > 0) {
                    // 指向AI角色时播放动画
                    this.aiCharacter.playAnimation('wave');
                }
            }
        }
    }

    // 处理角色交互
    handleCharacterInteraction(character = null) {
        console.log('🎭 角色交互触发', character);
        
        // 如果没有传入角色，使用默认的AI角色
        const targetCharacter = character || this.aiCharacter;
        
        if (targetCharacter) {
            // 播放问候动画
            if (targetCharacter.playAnimation) {
                targetCharacter.playAnimation('wave');
            }
            
            // 获取角色信息
            const characterName = targetCharacter.userData?.name || '诗人';
            const characterType = targetCharacter.userData?.characterType || 'default';
            
            // 显示交互提示
            if (this.uiManager) {
                this.uiManager.showNotification(`${characterName}向你问好！`, 'info');
            }
            
            // 在VR模式下激活对话模式
            if (this.isVRMode && this.unifiedXRManager && this.unifiedXRManager.handTrackingManager) {
                console.log('VR对话模式已激活');
            }
            
            // 根据角色类型执行特定交互
            this.executeCharacterSpecificInteraction(characterType, targetCharacter);
        }
    }
    
    // 执行角色特定的交互逻辑
    executeCharacterSpecificInteraction(characterType, character) {
        switch (characterType) {
            case 'poet':
                console.log('🎭 与诗人角色交互');
                // 可以触发诗歌朗诵或创作
                break;
            case 'philosopher':
                console.log('🤔 与哲学家角色交互');
                // 可以触发哲学思辨对话
                break;
            case 'artist':
                console.log('🎨 与艺术家角色交互');
                // 可以触发艺术创作或欣赏
                break;
            default:
                console.log('👋 通用角色交互');
                break;
        }
    }

    // 高亮角色
    highlightCharacter(highlight) {
        if (this.aiCharacter && this.aiCharacter.model) {
            if (highlight) {
                // 添加高亮效果
                this.aiCharacter.model.traverse((child) => {
                    if (child.isMesh && child.material) {
                        if (!child.userData.originalEmissive) {
                            child.userData.originalEmissive = child.material.emissive.clone();
                        }
                        child.material.emissive.setHex(0x444444);
                    }
                });
                console.log('✨ 角色高亮开启');
            } else {
                // 移除高亮效果
                this.aiCharacter.model.traverse((child) => {
                    if (child.isMesh && child.material && child.userData.originalEmissive) {
                        child.material.emissive.copy(child.userData.originalEmissive);
                    }
                });
                console.log('✨ 角色高亮关闭');
            }
        }
    }

    // 切换环境
    async switchEnvironment() {
        try {
            // 仅保留默认环境；3DGS环境已移除
            this.settings.environmentType = 'default';
            this.uiManager.showNotification('使用默认环境（3DGS已移除）', 'info');
            
            // 清理当前环境（如有自定义资源）
            
            // 重新初始化环境
            await this.initEnvironment();
            
        } catch (error) {
            console.error('环境切换失败:', error);
            this.uiManager.showNotification('环境切换失败', 'error');
        }
    }

    // 切换角色
    async switchCharacter(characterType = null) {
        try {
            // 如果没有指定角色类型，使用当前选中的角色
            if (!characterType && this.environmentPanel) {
                characterType = this.environmentPanel.currentCharacter;
            }
            
            if (!characterType) {
                console.warn('未指定角色类型');
                return;
            }

            this.uiManager.showNotification('正在切换角色...', 'info');
            
            // 调用后端API切换诗人角色
            try {
                const apiUrl = appConfig.getApiUrl();
                const response = await fetch(`${apiUrl}/api/poet/switch/${characterType}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`切换诗人角色失败: ${response.statusText}`);
                }
                
                const result = await response.json();
                console.log('后端诗人角色切换成功:', result);
            } catch (apiError) {
                console.warn('后端诗人角色切换失败:', apiError);
                // 继续执行前端角色切换，即使后端切换失败
            }
            
            // 销毁当前角色
            if (this.aiCharacter) {
                this.aiCharacter.dispose();
                this.aiCharacter = null;
            }

            // 使用PoetSelector切换诗人
            if (this.poetSelector) {
                await this.poetSelector.selectPoet(characterType);
            } else {
                console.warn('PoetSelector未初始化，无法切换诗人');
            }
            
            this.uiManager.showNotification(`已切换到${characterType}角色`, 'success');
            console.log(`角色已切换到: ${characterType}`);
            
        } catch (error) {
            console.error('角色切换失败:', error);
            this.uiManager.showNotification('角色切换失败', 'error');
        }
    }

    updateSettings(settings) {
        // 更新语音管理器设置
        if (this.voiceManager) {
            this.voiceManager.updateSettings(settings);
        }
        
        // 更新UI管理器设置
        if (this.uiManager) {
            this.uiManager.updateSettings(settings);
        }
        
        console.log('设置已更新:', settings);
    }

    hideLoadingScreen() {
        if (this.uiManager) {
            this.uiManager.hideLoading();
        } else {
            // 备用方法
            this.elements.loadingScreen.style.opacity = '0';
            setTimeout(() => {
                this.elements.loadingScreen.style.display = 'none';
            }, 500);
        }
    }

    onWindowResize() {
        // 在VR会话期间不应该调用setSize，因为WebXR会自动管理渲染器尺寸
        if (this.renderer.xr.isPresenting) {
            console.log('VR会话期间跳过窗口尺寸调整');
            return;
        }
        
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
    }

    onVRModeChange() {
        if (this.isVRMode) {
            // VR模式下的调整 - 使用统一XR管理器的UI管理
            console.log('进入VR模式 - 启用沉浸式体验');
            
            // 如果统一XR管理器可用，让它处理UI隐藏
            if (this.unifiedXRManager && this.unifiedXRManager.isXRActive) {
                // 统一XR管理器会自动处理UI隐藏
                console.log('统一XR管理器正在处理UI管理');
            } else {
                // 备用方案：手动隐藏UI
                this.hideUIForVR();
            }
            
            // 优化VR性能
            this.optimizeForVR();
            
        } else {
            // 退出VR模式
            console.log('退出VR模式 - 恢复常规界面');
            
            // 如果统一XR管理器可用，让它处理UI恢复
            if (this.unifiedXRManager) {
                // 统一XR管理器会自动处理UI恢复
                console.log('统一XR管理器正在处理UI恢复');
            } else {
                // 备用方案：手动恢复UI
                this.restoreUIFromVR();
            }
            
            // 恢复常规性能设置
            this.restoreNormalPerformance();
        }
    }
    
    /**
     * 备用方案：手动隐藏VR模式下的UI
     */
    hideUIForVR() {
        const elementsToHide = [
            'control-panel',
            'status-indicator',
            'subtitles',
            'error-modal'
        ];
        
        elementsToHide.forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.style.display = 'none';
            }
        });
        
        // 隐藏鼠标光标
        document.body.style.cursor = 'none';
        
        console.log('UI已隐藏（备用方案）');
    }
    
    /**
     * 备用方案：手动恢复VR模式后的UI
     */
    restoreUIFromVR() {
        const elementsToRestore = [
            'control-panel',
            'status-indicator',
            'subtitles'
        ];
        
        elementsToRestore.forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.style.display = 'block';
            }
        });
        
        // 恢复鼠标光标
        document.body.style.cursor = 'default';
        
        console.log('UI已恢复（备用方案）');
    }
    
    /**
     * 优化VR性能
     */
    optimizeForVR() {
        // 降低渲染质量以提高VR性能
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
        
        // 禁用阴影以提高性能
        this.renderer.shadowMap.enabled = false;
        
        // 减少环境光强度
        if (this.ambientLight) {
            this.ambientLight.intensity = 0.3;
        }
        
        console.log('VR性能优化已应用');
    }
    
    /**
     * 恢复常规性能设置
     */
    restoreNormalPerformance() {
        // 恢复正常渲染质量
        this.renderer.setPixelRatio(window.devicePixelRatio);
        
        // 重新启用阴影
        this.renderer.shadowMap.enabled = true;
        
        // 恢复环境光强度
        if (this.ambientLight) {
            this.ambientLight.intensity = 0.6;
        }
        
        console.log('常规性能设置已恢复');
    }

    animate() {
        // 确保只有一个渲染循环
        if (this.isAnimating) {
            return;
        }
        this.isAnimating = true;
        console.log('✅ 渲染循环开始');
        
        this.renderer.setAnimationLoop((time, frame) => {
            const delta = this.clock.getDelta();
            
            // 性能管理更新
            if (this.performanceManager) {
                this.performanceManager.update();
            }
            
            // 更新帧计数器
            this.frameSkipCounter++;
            const shouldSkipFrame = this.shouldSkipFrame();
            
            // 更新所有动画系统
            this.updateAnimations(delta, shouldSkipFrame);
            
            // 更新沉浸式体验系统
            if (this.immersiveExperience) {
                this.immersiveExperience.sceneManager.update();
                if (typeof this.immersiveExperience.updatePerformanceStats === 'function') {
                    this.immersiveExperience.updatePerformanceStats();
                }
            }
            
            // 更新统一WebXR管理器
            if (this.unifiedXRManager && (this.renderer.xr.isPresenting || this.unifiedXRManager.isXRActive)) {
                this.unifiedXRManager.update(delta, time, frame);
            }
            
            // 手势处理已统一到HandTrackingManager中
            
            // 更新动画混合器
            if (this.mixer) {
                this.mixer.update(delta);
            }
            
            // 根据性能决定是否跳过非关键更新
            if (!shouldSkipFrame) {
                // 更新控制器
                if (!this.isVRMode && this.controls) {
                    this.controls.update();
                }
                
                // 更新AI角色动画
                if (this.aiCharacter) {
                    this.aiCharacter.update();
                }

                // 更新3D诗人角色动画
                if (this.poet3DCharacter) {
                    this.poet3DCharacter.update();
                }
            }
            
            // 始终进行渲染，确保画面连续性
            this.renderer.render(this.scene, this.camera);
        });
    }

    /**
     * 统一的动画更新系统
     */
    updateAnimations(delta, shouldSkipFrame) {
        const time = Date.now() * 0.001;
        
        // 更新装饰动画
        if (this.decorations && !shouldSkipFrame) {
            this.decorations.forEach(decoration => {
                if (decoration.userData.originalY !== undefined) {
                    decoration.position.y = decoration.userData.originalY + 
                        Math.sin(time * decoration.userData.speed) * decoration.userData.amplitude;
                    decoration.rotation.y += 0.01;
                }
            });
        }
        
        // 更新呼吸动画
        if (this.aiCharacter && this.breathingAnimation) {
            const scale = 1 + Math.sin(time * 2) * 0.02;
            this.aiCharacter.scale.y = scale;
        }
        
        // 更新相机动画
        if (this.cameraAnimation) {
            this.updateCameraAnimation();
        }
        
        // 更新角色动画
        if (this.aiCharacter && !shouldSkipFrame) {
            this.updateCharacterAnimations(time);
        }
    }

    /**
     * 更新角色动画
     */
    updateCharacterAnimations(time) {
        if (!this.aiCharacter || !this.aiCharacter.character) return;
        
        const currentTime = Date.now();
        const character = this.aiCharacter.character;
        
        // 处理弹跳动画
        if (character.userData && character.userData.bounceAnimation) {
            const anim = character.userData.bounceAnimation;
            const elapsed = currentTime - anim.startTime;
            const progress = Math.min(elapsed / anim.duration, 1);
            
            if (progress < 0.5) {
                character.position.y = anim.originalY + Math.sin(progress * Math.PI * 4) * 0.2;
            } else {
                character.position.y = anim.originalY;
            }
            
            if (progress >= 1) {
                delete character.userData.bounceAnimation;
            }
        }
        
        // 处理思考动画
        if (character.userData && character.userData.thinkingAnimation) {
            const anim = character.userData.thinkingAnimation;
            const elapsed = currentTime - anim.startTime;
            const progress = Math.min(elapsed / anim.duration, 1);
            
            character.rotation.y = anim.originalRotationY + Math.sin(progress * Math.PI * 4) * 0.1;
            
            if (progress >= 1) {
                character.rotation.y = anim.originalRotationY;
                delete character.userData.thinkingAnimation;
            }
        }
        
        // 处理挥手动画
        const rightArm = character.children && character.children.find ? character.children.find(child => 
            child.position.x > 0 && child.geometry instanceof THREE.CylinderGeometry
        ) : null;
        
        if (rightArm && rightArm.userData && rightArm.userData.waveAnimation) {
            const anim = rightArm.userData.waveAnimation;
            const elapsed = currentTime - anim.startTime;
            const progress = Math.min(elapsed / anim.duration, 1);
            
            rightArm.rotation.z = anim.originalRotationZ + Math.sin(progress * Math.PI * 6) * 0.5;
            
            if (progress >= 1) {
                rightArm.rotation.z = anim.originalRotationZ;
                delete rightArm.userData.waveAnimation;
            }
        }
    }

    /**
     * 停止渲染循环
     */
    stopAnimation() {
        if (this.renderer) {
            this.renderer.setAnimationLoop(null);
        }
        this.isAnimating = false;
    }
    
    /**
     * 判断是否应该跳过当前帧的非关键更新
     */
    shouldSkipFrame() {
        if (!this.adaptiveFrameRate || !this.performanceManager) {
            return false;
        }
        
        const currentFPS = this.performanceManager.stats.fps;
        
        // 根据帧率决定跳帧策略，但更保守以避免闪动
        if (currentFPS < 20) {
            return this.frameSkipCounter % 4 !== 0; // 跳过3/4的非关键更新
        } else if (currentFPS < 30) {
            return this.frameSkipCounter % 3 !== 0; // 跳过2/3的非关键更新
        } else if (currentFPS < 45) {
            return this.frameSkipCounter % 2 !== 0; // 跳过1/2的非关键更新
        }
        
        return false; // 帧率足够时不跳过
    }

    /**
     * 计算帧跳过数量以维持目标帧率（保留用于兼容性）
     */
    calculateFrameSkip() {
        if (!this.performanceManager) return 1;
        
        const currentFPS = this.performanceManager.stats.fps;
        
        if (currentFPS < 30) {
            return 3; // 跳过2/3的帧
        } else if (currentFPS < 45) {
            return 2; // 跳过1/2的帧
        } else {
            return 1; // 不跳过帧
        }
    }
    // 初始化环境控制面板








    // 初始化沉浸式体验按钮




    // 创建增强的VR按钮
    createEnhancedVRButton() {
        // 检测设备类型
        const isVisionPro = this.detectVisionPro();
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        // 检查WebXR支持
        const hasWebXR = 'xr' in navigator;
        const isSecureContext = window.isSecureContext || location.protocol === 'https:' || location.hostname === 'localhost';
        
        let vrButton;
        
        if (hasWebXR && isSecureContext) {
            // 为WebXR设置参考空间
            if (this.renderer && this.renderer.xr && typeof this.renderer.xr.setReferenceSpaceType === 'function') {
                this.renderer.xr.setReferenceSpaceType('local-floor');
            }

            // 创建带会话参数的VR按钮，启用hand-tracking
            const sessionInit = {
                requiredFeatures: ['local-floor'],
                optionalFeatures: ['hand-tracking', 'layers']
            };
            vrButton = VRButton.createButton(this.renderer, { sessionInit });
            
            // 自定义按钮文本和样式
            if (isVisionPro) {
                vrButton.textContent = '进入沉浸式体验';
            } else if (isMobile) {
                vrButton.textContent = '进入VR模式';
            } else {
                vrButton.textContent = '进入VR体验';
            }
            
            // WebXR会话状态由统一XR管理器处理，通过自定义事件通知
            // 避免重复绑定事件监听器
            
        } else {
            // 创建提示按钮（当WebXR不可用时）
            vrButton = document.createElement('button');
            vrButton.style.display = 'block';
            vrButton.style.position = 'relative';
            vrButton.style.cursor = 'pointer';
            vrButton.style.left = 'calc(50% - 75px)';
            vrButton.style.width = '150px';
            vrButton.style.margin = '0';
            vrButton.style.border = 'none';
            vrButton.style.padding = '12px 6px';
            vrButton.style.background = 'rgba(255, 193, 7, 0.8)';
            vrButton.style.color = '#000';
            vrButton.style.font = 'normal 13px sans-serif';
            vrButton.style.textAlign = 'center';
            vrButton.style.opacity = '1';
            vrButton.style.outline = 'none';
            vrButton.style.zIndex = '999';
            vrButton.style.borderRadius = '8px';
            vrButton.style.transition = 'all 0.3s ease';
            
            if (!hasWebXR) {
                vrButton.textContent = 'WebXR 不支持';
                vrButton.title = '您的浏览器不支持WebXR技术';
            } else if (!isSecureContext) {
                vrButton.textContent = '需要HTTPS连接';
                vrButton.title = 'WebXR需要HTTPS连接或localhost环境';
            }
            
            vrButton.addEventListener('click', () => {
                if (!hasWebXR) {
                    alert('您的浏览器不支持WebXR技术。请使用支持WebXR的现代浏览器，如Chrome、Edge或Safari。');
                } else if (!isSecureContext) {
                    alert('WebXR需要安全连接（HTTPS）才能工作。请使用HTTPS访问此页面，或在localhost环境下使用。');
                }
            });
        }
        
        // 通用样式设置
        if (isVisionPro && vrButton) {
            vrButton.style.background = hasWebXR && isSecureContext ? 
                'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : 
                'rgba(255, 193, 7, 0.8)';
            vrButton.style.border = '2px solid rgba(255, 255, 255, 0.3)';
            vrButton.style.backdropFilter = 'blur(20px)';
            vrButton.style.borderRadius = '16px';
            vrButton.style.padding = '12px 24px';
            vrButton.style.fontSize = '16px';
            vrButton.style.fontWeight = '600';
            vrButton.style.color = hasWebXR && isSecureContext ? '#ffffff' : '#000000';
            vrButton.style.textShadow = hasWebXR && isSecureContext ? '0 1px 2px rgba(0, 0, 0, 0.3)' : 'none';
            vrButton.style.boxShadow = hasWebXR && isSecureContext ? 
                '0 8px 32px rgba(102, 126, 234, 0.4)' : 
                '0 4px 16px rgba(255, 193, 7, 0.4)';
            vrButton.style.transition = 'all 0.3s ease';
            
            // 添加悬停效果
            vrButton.addEventListener('mouseenter', () => {
                vrButton.style.transform = 'translateY(-2px) scale(1.05)';
                vrButton.style.boxShadow = hasWebXR && isSecureContext ? 
                    '0 12px 40px rgba(102, 126, 234, 0.6)' : 
                    '0 6px 20px rgba(255, 193, 7, 0.6)';
            });
            
            vrButton.addEventListener('mouseleave', () => {
                vrButton.style.transform = 'translateY(0) scale(1)';
                vrButton.style.boxShadow = hasWebXR && isSecureContext ? 
                    '0 8px 32px rgba(102, 126, 234, 0.4)' : 
                    '0 4px 16px rgba(255, 193, 7, 0.4)';
            });
        } else if (isMobile && vrButton) {
            vrButton.style.fontSize = '18px';
            vrButton.style.padding = '16px 32px';
        }
        
        return vrButton;
    }

    // 检测是否为Vision Pro设备
    detectVisionPro() {
        const userAgent = navigator.userAgent.toLowerCase();
        const isAppleDevice = /iphone|ipad|ipod|macintosh/.test(userAgent);
        const hasSafari = /safari/.test(userAgent) && !/chrome/.test(userAgent);
        const hasWebXR = 'xr' in navigator;
        
        // Vision Pro特征检测
        const hasVisionProFeatures = (
            isAppleDevice &&
            hasSafari &&
            hasWebXR &&
            window.screen.width >= 3840 && // Vision Pro的高分辨率
            'ontouchstart' in window
        );
        
        return hasVisionProFeatures;
    }

    // Vision Pro优化
    optimizeForVisionPro() {
        // 提高渲染质量
        this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        
        // 启用高质量阴影
        this.renderer.shadowMap.enabled = true;
        this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        
        // 优化光照
        if (this.scene.children.find(child => child.isDirectionalLight)) {
            const directionalLight = this.scene.children.find(child => child.isDirectionalLight);
            directionalLight.castShadow = true;
            directionalLight.shadow.mapSize.width = 2048;
            directionalLight.shadow.mapSize.height = 2048;
        }
        
        console.log('已为Vision Pro优化渲染设置');
    }

    // 设置OrbitControls
    setupOrbitControls() {
        if (!this.controls) return;
        
        // 基础设置
        this.controls.enableDamping = true;
        this.controls.dampingFactor = 0.05;
        this.controls.target.set(0, 1, 0);
        
        // 检测设备类型并优化控制
        const isVisionPro = this.detectVisionPro();
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        const isTouch = 'ontouchstart' in window;
        
        if (isVisionPro) {
            // Vision Pro优化设置
            this.controls.enablePan = true;
            this.controls.enableZoom = true;
            this.controls.enableRotate = true;
            this.controls.autoRotate = false;
            this.controls.autoRotateSpeed = 0.5;
            
            // 更平滑的阻尼
            this.controls.dampingFactor = 0.03;
            
            // 限制缩放范围
            this.controls.minDistance = 2;
            this.controls.maxDistance = 20;
            
            // 限制垂直旋转角度
            this.controls.minPolarAngle = Math.PI / 6; // 30度
            this.controls.maxPolarAngle = Math.PI - Math.PI / 6; // 150度
            
        } else if (isMobile || isTouch) {
            // 移动设备优化
            this.controls.enablePan = true;
            this.controls.enableZoom = true;
            this.controls.enableRotate = true;
            
            // 触摸设备的特殊设置
            this.controls.touches = {
                ONE: THREE.TOUCH.ROTATE,
                TWO: THREE.TOUCH.DOLLY_PAN
            };
            
            // 更快的阻尼响应
            this.controls.dampingFactor = 0.08;
            
            // 适合移动设备的缩放范围
            this.controls.minDistance = 3;
            this.controls.maxDistance = 15;
            
        } else {
            // 桌面设备优化
            this.controls.enablePan = true;
            this.controls.enableZoom = true;
            this.controls.enableRotate = true;
            
            // 鼠标控制设置
            this.controls.mouseButtons = {
                LEFT: THREE.MOUSE.ROTATE,
                MIDDLE: THREE.MOUSE.DOLLY,
                RIGHT: THREE.MOUSE.PAN
            };
            
            // 标准阻尼设置
            this.controls.dampingFactor = 0.05;
            
            // 桌面设备的缩放范围
            this.controls.minDistance = 1;
            this.controls.maxDistance = 25;
        }
        
        // 通用设置
        this.controls.screenSpacePanning = false;
        this.controls.enableKeys = true;
        this.controls.keys = {
            LEFT: 'ArrowLeft',
            UP: 'ArrowUp', 
            RIGHT: 'ArrowRight',
            BOTTOM: 'ArrowDown'
        };
        
        // 添加控制器事件监听
        this.controls.addEventListener('change', () => {
            // 在非VR模式下更新渲染
            if (!this.isVRMode) {
                this.renderer.render(this.scene, this.camera);
            }
        });
        
        console.log('OrbitControls已配置完成，设备类型:', {
            isVisionPro,
            isMobile,
            isTouch
        });
    }

    // 清理资源
    dispose() {
        // 清理性能管理器
        if (this.performanceManager) {
            this.performanceManager.dispose();
        }
        
        // 清理统一WebXR管理器
        if (this.unifiedXRManager) {
            this.unifiedXRManager.dispose();
        }
        
        // 手势处理已统一到HandTrackingManager中
        
        // 清理3DGS环境
        // 3DGS环境已移除
        
        // 清理环境控制面板
        if (this.environmentPanel) {
            this.environmentPanel.dispose();
        }
        
        // 清理设置按钮
        if (this.settingsButton) {
            this.settingsButton.destroy();
        }
        
        // 清理AI角色
        if (this.aiCharacter) {
            this.aiCharacter.dispose();
        }
        
        // 清理音频管理器
        if (this.audioManager) {
            this.audioManager.dispose();
        }
        
        // 清理语音管理器
        if (this.voiceManager) {
            this.voiceManager.dispose();
        }
        
        // 清理Three.js资源
        if (this.renderer) {
            this.renderer.dispose();
        }
        
        console.log('Vision Pro AI场景资源已清理');
    }
}



// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 创建应用实例并赋值给window.app，确保全局可访问
    window.app = new VisionProAIScene();
});